package com.common;

import com.google.protobuf.ServiceException;
import com.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;

@ControllerAdvice
@Slf4j
public class ExceptionAdvice {
    public static final String HTTP_HEADS = "headers";
    public static final String HTTP_PARAMS = "parameters";
    public static final String HTTP_URL = "url";

    @ExceptionHandler(value = {ServiceException.class})
    @ResponseBody
    public BaseResult<?> serviceExceptionHandler(HttpServletRequest request , ServiceException e, HttpServletResponse response){
        HashMap<String, String> requestInfo = getBasicRequestInfo(request);
        log.error("Exception handling request ");
        response.setStatus(HttpServletResponse.SC_OK);
        return BaseResult.fail(e.getMessage());
    }

    /**
     * 获取HTTP基本信息，包括URL,HEAD,QUERY STRING
     *
     * @param request
     * @return
     */
    private HashMap<String, String> getBasicRequestInfo(HttpServletRequest request) {

        StringBuilder headers = null;
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            if (headers == null) {
                headers = new StringBuilder();
            } else {
                headers.append("\r\n");
            }
            String headerName = headerNames.nextElement();
            headers.append("    " + headerName + "=" + request.getHeader(headerName));
        }
        headers = (headers == null) ? new StringBuilder() : headers;

        StringBuilder params = null;
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            if (params == null) {
                params = new StringBuilder();
            } else {
                headers.append("\r\n");
            }
            String paramName = parameterNames.nextElement();
            params.append("    " + paramName + "=" + request.getParameter(paramName));
        }

        params = (params == null) ? new StringBuilder() : params;
        String url = request.getContextPath() + request.getServletPath();

        HashMap<String, String> map = new HashMap<>();
        map.put(HTTP_HEADS, headers.toString());
        map.put(HTTP_PARAMS, params.toString());
        map.put(HTTP_URL, url);

        return map;
    }

}
